#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
海岛生存模拟器 - 主程序入口
Island Survival Simulator - Main Entry Point
"""

import pygame
import sys
import random
from enum import Enum
from dataclasses import dataclass
from typing import List, Tuple, Dict, Optional
import math
import os

# 初始化pygame
pygame.init()

# 游戏配置
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
FPS = 60
TILE_SIZE = 32

# 颜色定义
COLORS = {
    'water': (64, 164, 223),
    'sand': (238, 214, 175),
    'grass': (34, 139, 34),
    'forest': (0, 100, 0),
    'rock': (128, 128, 128),
    'player': (255, 0, 0),
    'text': (255, 255, 255),
    'black': (0, 0, 0),
    'ui_bg': (50, 50, 50),
    'ui_border': (100, 100, 100)
}

class TileType(Enum):
    WATER = 0
    SAND = 1
    GRASS = 2
    FOREST = 3
    ROCK = 4

class ResourceType(Enum):
    WOOD = "木材"
    STONE = "石头"
    FOOD = "食物"

@dataclass
class Player:
    x: int
    y: int
    health: int = 100
    hunger: int = 100
    inventory: Dict[str, int] = None
    
    def __post_init__(self):
        if self.inventory is None:
            self.inventory = {
                ResourceType.WOOD.value: 0,
                ResourceType.STONE.value: 0,
                ResourceType.FOOD.value: 0
            }

class Game:
    def __init__(self):
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption("海岛生存模拟器")
        self.clock = pygame.time.Clock()
        self.running = True
        
        # 字体支持
        self.font_cache = {}
        self.load_fonts()
        
        # 游戏状态
        self.game_state = "playing"  # playing, paused, game_over
        
        # 地图
        self.map_width = 50
        self.map_height = 50
        self.tile_map = [[TileType.WATER for _ in range(self.map_width)] 
                        for _ in range(self.map_height)]
        
        # 玩家
        self.player = Player(25, 25)
        
        # 建筑
        self.buildings = []
        
        # 环境事件
        self.event_timer = 0
        self.event_interval = 30000  # 30秒
        
        # 初始化游戏
        self.generate_island()
        
    def load_fonts(self):
        """加载字体，支持中文显示"""
        # 尝试多个系统字体路径
        font_paths = [
            "C:/Windows/Fonts/simhei.ttf",  # Windows 黑体
            "C:/Windows/Fonts/simsun.ttc",  # Windows 宋体
            "/System/Library/Fonts/STHeiti Medium.ttc",  # macOS
            "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",  # Linux
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"  # 通用
        ]
        
        self.chinese_font = None
        for font_path in font_paths:
            if os.path.exists(font_path):
                try:
                    self.chinese_font = font_path
                    break
                except:
                    continue
        
        if not self.chinese_font:
            self.chinese_font = None  # 使用默认字体
    
    def get_font(self, size):
        """获取字体对象"""
        if size not in self.font_cache:
            if self.chinese_font:
                self.font_cache[size] = pygame.font.Font(self.chinese_font, size)
            else:
                self.font_cache[size] = pygame.font.Font(None, size)
        return self.font_cache[size]
        
    def generate_island(self):
        """生成随机海岛地图"""
        # 创建基础地形
        center_x, center_y = self.map_width // 2, self.map_height // 2
        
        # 生成陆地
        for y in range(self.map_height):
            for x in range(self.map_width):
                distance = math.sqrt((x - center_x)**2 + (y - center_y)**2)
                if distance < 15:  # 岛屿半径
                    if distance < 8:
                        self.tile_map[y][x] = TileType.GRASS
                    elif distance < 12:
                        self.tile_map[y][x] = TileType.SAND
                    else:
                        # 随机生成森林或岩石
                        if random.random() < 0.6:
                            self.tile_map[y][x] = TileType.FOREST
                        else:
                            self.tile_map[y][x] = TileType.ROCK
        
        # 确保玩家出生在草地上
        self.player.x, self.player.y = center_x, center_y
        
    def handle_events(self):
        """处理游戏事件"""
        keys = pygame.key.get_pressed()
        
        # 相机移动
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.camera_x += self.camera_speed
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.camera_x -= self.camera_speed
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            self.camera_y += self.camera_speed
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            self.camera_y -= self.camera_speed
            
        # 限制相机范围
        max_camera_x = 0
        max_camera_y = 0
        min_camera_x = -(self.map_width * TILE_SIZE - SCREEN_WIDTH + 250)  # 考虑UI面板
        min_camera_y = -(self.map_height * TILE_SIZE - SCREEN_HEIGHT)
        
        self.camera_x = max(min_camera_x, min(max_camera_x, self.camera_x))
        self.camera_y = max(min_camera_y, min(max_camera_y, self.camera_y))
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.running = False
                elif event.key == pygame.K_e:
                    self.collect_resources()
                elif event.key == pygame.K_r and self.game_state == "game_over":
                    self.restart()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键
                    self.handle_click(event.pos)
                elif event.button == 4:  # 滚轮上
                    pass  # 可以添加缩放功能
                elif event.button == 5:  # 滚轮下
                    pass  # 可以添加缩放功能
                    
    def handle_click(self, pos):
        """处理鼠标点击"""
        mouse_x, mouse_y = pos
        
        # 考虑相机偏移计算点击的地图坐标
        world_x = mouse_x - self.camera_x
        world_y = mouse_y - self.camera_y
        
        map_x = int(world_x // TILE_SIZE)
        map_y = int(world_y // TILE_SIZE)
        
        # 检查是否在地图范围内
        if 0 <= map_x < self.map_width and 0 <= map_y < self.map_height:
            # 检查是否点击了资源
            tile = self.tile_map[map_y][map_x]
            if tile == TileType.FOREST:
                self.player.inventory[ResourceType.WOOD.value] += 1
                self.tile_map[map_y][map_x] = TileType.GRASS
            elif tile == TileType.ROCK:
                self.player.inventory[ResourceType.STONE.value] += 1
                self.tile_map[map_y][map_x] = TileType.SAND
            elif tile == TileType.GRASS:
                self.player.inventory[ResourceType.FOOD.value] += 1
                
    def collect_resources(self):
        """收集当前位置的资源"""
        x, y = int(self.player.x), int(self.player.y)
        if 0 <= x < self.map_width and 0 <= y < self.map_height:
            tile = self.tile_map[y][x]
            if tile == TileType.FOREST:
                self.player.inventory[ResourceType.WOOD.value] += 2
                self.tile_map[y][x] = TileType.GRASS
            elif tile == TileType.ROCK:
                self.player.inventory[ResourceType.STONE.value] += 2
                self.tile_map[y][x] = TileType.SAND
            elif tile == TileType.GRASS:
                self.player.inventory[ResourceType.FOOD.value] += 2
                
    def update(self, dt):
        """更新游戏状态"""
        if self.game_state != "playing":
            return
            
        # 更新玩家饥饿值
        self.player.hunger -= 0.01 * (dt / 1000)
        if self.player.hunger <= 0:
            self.player.health -= 0.1 * (dt / 1000)
            
        # 检查游戏结束条件
        if self.player.health <= 0:
            self.game_state = "game_over"
            
        # 更新环境事件
        self.event_timer += dt
        if self.event_timer >= self.event_interval:
            self.trigger_environment_event()
            self.event_timer = 0
            
    def trigger_environment_event(self):
        """触发环境事件"""
        events = ["storm", "beast_attack", "cold_wave"]
        event = random.choice(events)
        
        if event == "storm":
            # 风暴损坏建筑
            if self.buildings:
                building = random.choice(self.buildings)
                building["durability"] -= 20
            self.player.health -= 5
        elif event == "beast_attack":
            # 野兽攻击
            self.player.health -= 15
        elif event == "cold_wave":
            # 寒潮降低温度
            self.player.hunger -= 10
            
    def draw(self):
        """绘制游戏画面"""
        self.screen.fill(COLORS['water'])
        
        # 计算可见区域
        start_x = max(0, -self.camera_x // TILE_SIZE)
        end_x = min(self.map_width, (-self.camera_x + SCREEN_WIDTH) // TILE_SIZE + 1)
        start_y = max(0, -self.camera_y // TILE_SIZE)
        end_y = min(self.map_height, (-self.camera_y + SCREEN_HEIGHT) // TILE_SIZE + 1)
        
        # 绘制地图（只绘制可见部分）
        for y in range(start_y, end_y):
            for x in range(start_x, end_x):
                tile = self.tile_map[y][x]
                color = COLORS[tile.name.lower()]
                screen_x = x * TILE_SIZE + self.camera_x
                screen_y = y * TILE_SIZE + self.camera_y
                
                # 只绘制屏幕内的图块
                if -TILE_SIZE <= screen_x < SCREEN_WIDTH and -TILE_SIZE <= screen_y < SCREEN_HEIGHT:
                    rect = pygame.Rect(screen_x, screen_y, TILE_SIZE, TILE_SIZE)
                    pygame.draw.rect(self.screen, color, rect)
                    pygame.draw.rect(self.screen, COLORS['black'], rect, 1)
                
        # 绘制玩家（考虑相机偏移）
        player_screen_x = self.player.x * TILE_SIZE + self.camera_x
        player_screen_y = self.player.y * TILE_SIZE + self.camera_y
        
        player_rect = pygame.Rect(
            player_screen_x, 
            player_screen_y, 
            TILE_SIZE, 
            TILE_SIZE
        )
        pygame.draw.rect(self.screen, COLORS['player'], player_rect)
        
        # 绘制UI
        self.draw_ui()
        
    def draw_ui(self):
        """绘制用户界面"""
        # 资源面板
        ui_x = SCREEN_WIDTH - 250
        ui_y = 10
        
        # 背景
        ui_rect = pygame.Rect(ui_x, ui_y, 240, 200)
        pygame.draw.rect(self.screen, COLORS['ui_bg'], ui_rect)
        pygame.draw.rect(self.screen, COLORS['ui_border'], ui_rect, 2)
        
        # 标题
        font = self.get_font(36)
        title = font.render("生存状态", True, COLORS['text'])
        self.screen.blit(title, (ui_x + 10, ui_y + 10))
        
        # 资源信息
        font = self.get_font(24)
        y_offset = 50
        
        # 健康值
        health_text = font.render(f"生命值: {int(self.player.health)}", True, COLORS['text'])
        self.screen.blit(health_text, (ui_x + 10, ui_y + y_offset))
        y_offset += 30
        
        # 饥饿值
        hunger_text = font.render(f"饥饿值: {int(self.player.hunger)}", True, COLORS['text'])
        self.screen.blit(hunger_text, (ui_x + 10, ui_y + y_offset))
        y_offset += 30
        
        # 资源
        for resource, count in self.player.inventory.items():
            resource_text = font.render(f"{resource}: {count}", True, COLORS['text'])
            self.screen.blit(resource_text, (ui_x + 10, ui_y + y_offset))
            y_offset += 25
            
        # 相机位置信息
        cam_text = font.render(f"相机: {int(self.camera_x)}, {int(self.camera_y)}", True, COLORS['text'])
        self.screen.blit(cam_text, (ui_x + 10, ui_y + y_offset))
        y_offset += 25
            
        # 操作提示
        font_small = self.get_font(18)
        hint_text = font_small.render("WASD/方向键: 移动视角", True, COLORS['text'])
        self.screen.blit(hint_text, (ui_x + 10, ui_y + y_offset))
        y_offset += 20
        hint_text2 = font_small.render("鼠标点击: 收集资源", True, COLORS['text'])
        self.screen.blit(hint_text2, (ui_x + 10, ui_y + y_offset))
            
        # 游戏结束画面
        if self.game_state == "game_over":
            self.draw_game_over()
            
    def draw_game_over(self):
        """绘制游戏结束画面"""
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
        overlay.set_alpha(128)
        overlay.fill((0, 0, 0))
        self.screen.blit(overlay, (0, 0))
        
        font = self.get_font(72)
        game_over_text = font.render("游戏结束", True, COLORS['text'])
        text_rect = game_over_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2))
        self.screen.blit(game_over_text, text_rect)
        
        font = self.get_font(36)
        restart_text = font.render("按R键重新开始", True, COLORS['text'])
        restart_rect = restart_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 60))
        self.screen.blit(restart_text, restart_rect)
        
    def restart(self):
        """重新开始游戏"""
        self.__init__()
        
    def run(self):
        """游戏主循环"""
        while self.running:
            dt = self.clock.tick(FPS)
            
            self.handle_events()
            self.update(dt)
            self.draw()
            
            pygame.display.flip()
            
        pygame.quit()
        sys.exit()

if __name__ == "__main__":
    game = Game()
    game.run()
